package com.flower.controller;

import java.text.ParseException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.flower.pojo.Category;
import com.flower.pojo.Product;
import com.flower.service.IManageProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 管理员模块 ———— 商品管理
 */
@Controller
public class ManageProuctController {
	
	@Resource(name = "manageProductService")
	private IManageProductService iManageProductService;
	
	/**
	 * 商品修改
	 */
	@RequestMapping(value="/updateProduct.do")
	@ResponseBody
	/*
	 * @ResponseBody不会将@RequestMapping返回结果解析为跳转路径
	 * 而是通过HttpMessageConverter转换为指定格式后的结果（如json，xml等）
	 * 直接写入HTTP Response对象的body中，页面直接获取其返回值
	 * */
	public String updateProduct(Product product, HttpServletRequest request, Model model){
		//System.out.println(product);
		int row = iManageProductService.updateProduct(product);
		if(row > 0){
			return "OK";
		}else{
			return "FAIL";
		}
	}
	
	/**
	 * 商品添加
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/addProduct.do", method=RequestMethod.POST)
	public String addProduct(Product product, Category category, HttpServletRequest request) throws ParseException{
		product.setCategory(category);
		//重设图片路径
		String img = product.getPimage();
		product.setPimage("product/" + img);
		iManageProductService.insertProduct(product);
		
		return "redirect:/add_product.jsp";
	}
	
	/**
	 * 删除商品
	 */
	@RequestMapping("/deleteProduct.do")
	@ResponseBody
	public String deleteProduct(HttpServletRequest request, int pid){
		int row = iManageProductService.deleteProduct(pid);
		
		if(row > 0){
			return "OK";
		}else{
			return "FAIL";
		}
	}
	
	/**
	 * 商品展示
	 */
	@RequestMapping("/selectAllProduct.do")
	public String showProduct(@RequestParam(required=true, defaultValue="1") Integer startPage,
			Model model){
		PageHelper.startPage(startPage, 10);
		List<Product> products = iManageProductService.selectAllProduct();
		PageInfo<Product> pi = new PageInfo<Product>(products);
		//类似request.setAttribute()
		model.addAttribute("PAGE", pi);
		model.addAttribute("products", products);
		//转发2次跳转之间传输的信息不会丢失，重定向2次跳转之间传输的信息会丢失（request范围）
		return "show_products";
	}
	
}
